<?php

class CGame extends Zend_Db_Table{
	
	protected $_name;
	
	protected $_primary;

	public function __construct(){
		
		$this->_name=R_PRE."game";
		
		$this->_primary="joineremail";
		
		parent::__construct();
		
	}
	
	public function Join($data)
	{
		try {
			$joinerid=$this->insert($data);
		} catch (Exception $e) {
			throw new Exception('Sorry, you have joined. But you can share a jersey to your friends.');
		}
	
		return $joinerid;
	}
	
	public function GetJoinerCounts($where = '')
	{
		$db=$this->getAdapter();
		
		$select = $db->select();

		$select->from($this->_name,'COUNT(*)');
		
		if($where!=''){
			
			$select->where($where);
	
		}
		return $db->fetchOne($select);
	}
	
	/**
	 * 生成领奖的hash
	 */
	public function genHashCode($email, $jointime, $facebookid)
	{
		return md5($email . $jointime . $facebookid . 'newjerseysoccer');
	}
	
	/**
	 * 活动结束，后台生成hash和expiretime
	 */
	public function setHashCode($joiner, $expireTime)
	{
		$hash = $this->genHashCode($joiner->joineremail, $joiner->jointime, $joiner->facebookid);
		$where = $this->getAdapter()->quoteInto('joineremail = ?', $joiner->joineremail);
		$where .= ' and ' . $this->getAdapter()->quoteInto('jointime = ?', $joiner->jointime);
		$this->update(array('expiretime'=>$expireTime, 'hashcode'=>$hash), $where);
	}
	
	/**
	 * 判断一个hash是否有效
	 */
	public function isValidate($hashCode = NULL)
	{
		if (empty($hashCode)) {
			return false;
		}
		$row = $this->fetchRow(array('hashcode=?'=>$hashCode));
		if (!$row) {
			return false;
		}
		if ($row->isprize) {
			return false;
		}
		if (strtotime($row->expiretime) < time()) {
			return false;
		}
		return true;
	}
	
	public function GetAllJoiners($where = 'gametype=0')
	{
		$db=$this->getAdapter();
		
		$select = $db->select();

		$select->from($this->_name,'*');
		
		if($where!=''){
			
			$select->where($where);
	
		}
		return $db->fetchAll($select);
	}
	
	public function IsJoin($facebookid)
	{
		$db=$this->getAdapter();
		
		$select = $db->select();

		$select->from($this->_name,'*');
			
		$select->where('facebookid='.$facebookid);
		
		return $db->fetchRow($select);
	}
}